import socket
import threading



class HttpSocket(object):
    def __init__(self):
        server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        server_socket.bind(("",8080))
        server_socket.listen(128)
        self.server_socket = server_socket

    def main(self):
        while True:
            new_socket, new_address = self.server_socket.accept()
            threading.Thread(target=self.func, args=(new_socket, new_address)).start()

    @staticmethod
    def func(new_socket, new_address):
        print(f"{str(new_address)}已上线")
        recv_data = new_socket.recv(4096)
        if not recv_data:
            print("对方已下线")
            return
        show_info = recv_data.decode().split(" ")[1]

        if show_info == "/":
            show_info = "/index.html"

        try:
            with open("baoke" + show_info,"rb") as file:
                file_data = file.read()
        except:
            with open("baoke/404.html","rb") as file:
                file_data = file.read()
            html_data = "HTTP/1.1 404NotFound\r\nServer: PWS\r\n\r\n".encode() + file_data
        else:
            html_data = "HTTP/1.1 200OK\r\nServer: PWS\r\n\r\n".encode() + file_data
        finally:
            new_socket.send(html_data)
            new_socket.close()
if __name__ == '__main__':
    http_socket = HttpSocket()
    http_socket.main()


